<template>
  <el-dialog
    :title="!form.userId ? '添加用户' : '修改用户'"
    :close-on-click-modal="false"
    v-model="isShow"
    width="600px"
    @close="close"
  >
    <el-form ref="rulesForm" :model="form" :rules="rules" label-width="80px">
      <div class="user-form search-form2">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item v-if="!form.userId" label="密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="用户性别" prop="sex">
          <el-select v-model="form.sex" clearable placeholder="请选择">
            <el-option
              label="男"
              value="0"
            />
            <el-option
              label="女"
              value="1"
            />
            <el-option
              label="未知"
              value="2"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="enable">
          <el-radio v-model="form.enable" :label="1">正常</el-radio>
          <el-radio v-model="form.enable" :label="0">停用</el-radio>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select
            v-model="form.roleIds"
            multiple
            collapse-tags
            placeholder="请选择">
            <el-option
              v-for="(item, key) in roleOptions"
              :key="key"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width:100%;">
          <el-input v-model="form.remark" type="textarea" :rows="2"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { useStore } from 'vuex'
import { reactive, watch, computed, toRefs, ref, defineComponent } from 'vue'
import { ElMessage } from 'element-plus'
import dialog from '@/mixins/dialog'
import { StateType as UserStateType, User } from '@/store/modules/system/user'
import { Role } from '@/store/modules/system/role'

interface DataType {
  form: User;
  rules: object;
}

export default defineComponent({
  name: 'AUUser',
  emits: ['onRefresh', 'close'], // this line
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {
    const { dialogM } = dialog(props, context)
    const store = useStore<{user: UserStateType}>()
    const data = reactive<DataType>({
      form: {
        userId: null,
        username: '',
        nickName: '',
        userType: '',
        email: '',
        phoneNumber: '',
        sex: '',
        avatar: '',
        enable: true,
        roleIds: []
      },
      rules: {
        username: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phoneNumber: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      }
    })
    const rulesForm = ref<HTMLElement>()
    const userData = computed<User>(() => {
      return store.state.user.data
    })
    const roleOptions = computed<Array<Role>>(() => {
      return store.state.user.roleOptions
    })
    watch(() => props.value, (val) => {
      if (val) {
        if (userData.value) {
          data.form = JSON.parse(JSON.stringify(userData.value))
          data.form.roleIds = userData.value.roleIds
        }
      } else {
        data.form = {
          userId: null,
          username: '',
          nickName: '',
          userType: '',
          email: '',
          phoneNumber: '',
          sex: '',
          avatar: '',
          enable: true,
          roleIds: []
        }
        store.commit('user/SET_DATA', null)
        rulesForm.value && (rulesForm.value as any).resetFields()
      }
    })
    const submit = () => {
      rulesForm.value && (rulesForm.value as any).validate((valid: boolean) => {
        if (valid) {
          if (data.form.userId) {
            store.dispatch('user/updateUser', data.form).then(() => {
              ElMessage({
                message: '修改成功',
                type: 'success'
              })
              context.emit('onRefresh')
              dialogM.close()
            })
          } else {
            store.dispatch('user/insertUser', data.form).then(() => {
              ElMessage({
                message: '新增成功',
                type: 'success'
              })
              context.emit('onRefresh')
              dialogM.close()
            })
          }
        }
      })
    }
    return {
      roleOptions,
      ...toRefs(dialogM),
      ...toRefs(data),
      rulesForm,
      submit
    }
  }
})
</script>
